package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class BuildsTheHeapUsingTheHeapifyMethod {
	public static void buildHeap(Comparable[] heap, int heapSize) {
		for (int i = heapSize / 2; i > 0; i--) {
			heapify(heap, i, heapSize);
		}
	}


	public static void heapify(Comparable[] heap, int index, int heapSize) {
		int leftIndex = 2 * index;
		int rightIndex = 2 * index + 1;
		if (leftIndex <= heapSize) {
			if (heap[leftIndex].compareTo(heap[index]) > 0) {
				swap(heap, index, leftIndex);
				heapify(heap, leftIndex, heapSize);
			}
		}
		if (rightIndex <= heapSize) {
			if (heap[rightIndex].compareTo(heap[index]) > 0) {
				swap(heap, index, rightIndex);
				heapify(heap, rightIndex, heapSize);
			}
		}
	}


	public static void swap(Comparable[] heap, int index, int index2) {
		Comparable temp = heap[index];
		heap[index] = heap[index2];
		heap[index2] = temp;
	}
}
